<template>
  <div class="canvasParent">
    <div class="selectBox">
      <span class="TXHeader">当前体系架构：</span>
      <el-select v-model="TXvalue" size="small" style="min-width: 300px;" filterable placeholder="请选择">
        <el-option
          v-for="item in TXAllInformation"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <span style="display: inline-block;width: 20px;"></span>
      <el-button size="small" type="primary" icon="el-icon-refresh" circle @click="load3DView"></el-button>
      <el-button size="small" type="success" icon="el-icon-scissors" v-show="!isPiecesData" @click="spliceData"
                 circle></el-button>
      <el-button size="small" type="danger" icon="el-icon-scissors" v-show="isPiecesData" @click="closeSpliceData"
                 circle></el-button>
    </div>
    <canvas ref="renderCanvas" id="renderCanvas"></canvas>

    <el-button type="primary" class="small btn_Download" icon="el-icon-download"
               @click="downloadSystemStructure">三维体系架构导出
    </el-button>
    <el-button class="small btn_prewUp" v-show="!showUnitUnfold" icon="el-icon-caret-left" @click="prewUp">
      返回上级
    </el-button>
    <el-button type="warning" class="small btn_Location" icon="el-icon-map-location" @click="unitLocation">
      单元定位
    </el-button>

    <div class="floatingFrame">
      <div class="main" style="position:relative;">
        <span @click="unitInformationClose" style="position: absolute;
        cursor: pointer;
        top:0px;
        right: 0px;
        z-index: 999;
        display: inline-block;
        font-size: 40px;
        font-weight: 700;
         line-height: 40px;
         text-shadow: 0 1px 2px rgba(0,0,0,.1);
        -moz-transform: rotate(45deg);
         -webkit-transform: rotate(45deg);">+</span>
        <h3 class="title">单元信息：</h3>
        <el-form class="unitForm" ref="form" :model="keys" label-width="100px">
          <el-form-item :label="keys.xName">
            <el-input v-model="keys.x" disabled size="mini"></el-input>
          </el-form-item>
          <el-form-item :label="keys.yName">
            <el-input v-model="keys.y" disabled size="mini"></el-input>
          </el-form-item>
          <el-form-item :label="keys.zName">
            <el-input v-model="keys.z" disabled size="mini"></el-input>
          </el-form-item>
          <el-form-item label="含义">
            <el-input type="textarea"
                      :rows="2" placeholder="请输入内容" v-model="keys.mean" size="mini"></el-input>
          </el-form-item>
          <!--          <el-form-item label="属性">-->
          <!--            <el-input v-model="keys.xx" size="mini"></el-input>-->
          <!--          </el-form-item>-->
<!--          <el-form-item label="指标">-->
<!--            <el-input v-model="keys.target" size="mini"></el-input>-->
<!--          </el-form-item>-->
          <el-col  v-for="(domain) in keys.attributes"
                   :key="domain.key">
            <el-col :span="9">
              <el-form-item
                label="属性：">
                <el-select v-model="domain.attributeTypeId" size="mini" placeholder="请选择" @change="attrTypeChange">
                  <el-option
                    v-for="item in attrTypeAllData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item label="指标：">
                <el-autocomplete
                  class="inline-input"
                  v-model="domain.val"
                  size="mini"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  clearable
                  @select="handleSelect"
                >
                </el-autocomplete>
                <span style="width: 20px;display: inline-block;"> </span>
                <el-button type="danger" size="mini" v-show="!(domain.type===1)" @click.prevent="removeUnit(domain)">删除</el-button>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col>
            <el-form-item>
              <el-button @click="addAttr()" >添加属性</el-button>
              <el-button class="center-align" type="success"  @click="unitSaveOrUpdate">保存</el-button>
              <el-button class="center-align" v-show="showUnitUnfold" type="primary" @click="showUnitOr3DView">单元展开
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </div>

    <!--    单元定位弹出层   -->
    <el-dialog :title="'单元定位'" :visible.sync="unitLocationIsShow" width="80%">
      <el-row>
        <span class="LHeader">{{ locationXData.name }}：</span>
        <el-select v-model="xLocation" size="mini" filterable placeholder="请选择">
          <el-option
            v-for="item in xData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <span class="LHeader">{{ locationYData.name }}：</span>
        <el-select v-model="yLocation" size="mini" filterable placeholder="请选择">
          <el-option
            v-for="item in yData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <span class="LHeader">{{ locationZData.name }}：</span>
        <el-select v-model="zLocation" size="mini" filterable placeholder="请选择">
          <el-option
            v-for="item in zData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <span style="display: inline-block;width: 20px;"></span>
        <el-button class="primary" type="primary" @click="queryUnit">定位</el-button>
      </el-row>
      <br>
      <el-row>
        <el-form ref="form" :model="locationForm" label-width="80px">
<!--          <el-form-item label="名称：">-->
<!--            <el-input v-model="locationForm.name" size="mini"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="含义：">
            <el-input type="textarea"
                      :rows="2" placeholder="请输入内容" v-model="locationForm.mean"></el-input>
          </el-form-item>
          <el-col  v-for="(local) in locationForm.attributes"
                   :key="local.key">
            <el-col :span="10">
              <el-form-item
                label="属性：">
                <el-select v-model="local.attributeTypeId" size="mini" placeholder="请选择" @change="attrTypeChange">
                  <el-option
                    v-for="item in attrTypeAllData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="指标：">
                <el-autocomplete
                  class="inline-input"
                  v-model="local.val"
                  size="mini"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  clearable
                  @select="handleSelect"
                >
                </el-autocomplete>
                <span style="width: 20px;display: inline-block;"> </span>
                <el-button type="danger" size="mini" v-show="!(local.type===1)" @click.prevent="removeLocalUnit(local)">删除</el-button>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col>
            <el-form-item>
              <el-button @click="addLocationAttr()">添加属性</el-button>
              <el-button class="center-align" type="success" @click="locationUnitSave">保存</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
    <scaleDialog :visible.sync="scaleShowDialog" @close="scaleShowDialog = false"></scaleDialog>
  </div>
</template>

<script>
import vb from 'vue-babylonjs'
import html2canvas from 'html2canvas'
import { getSysAll, getTXTree } from '@api/sys.controller'
import { getUnit, saveUnit } from '@api/unit'
import scaleDialog from './scaleDialog'
import util from '@/libs/util'
import { getAttrTypeAll } from '@api/attr.type'
import { getAttrList } from '@api/attr'
// import * as GUI from 'babylonjs-gui'
import Docx from 'docxtemplater'
import JSzip from 'jszip'
import { saveAs } from 'file-saver'
import JSZipUtils from 'jszip-utils'
import htmlDocx from 'html-docx-js/dist/html-docx'

export default {
  name: 'boxs',
  components: {
    scaleDialog
  },
  data () {
    return {
      arr : [],
      xRotate: 7,
      isPiecesData: false,
      xLocation: '',
      xData: [{}],
      yLocation: '',
      yData: [{}],
      zLocation: '',
      zData: [{}],
      locationXData: {},
      locationYData: {},
      locationZData: {},
      unitLocationIsShow: false,
      scaleShowDialog: false,
      sceneToRender: null,
      TXvalue: '',
      showUnitUnfold: true,
      TXAllInformation: [{}],
      keys: {
        attributes: []
      },
      currentUnitIds: [],
      currentUnitInformation: {},
      xVal: '',
      xFragment: [],
      yVal: '',
      yFragment: [],
      zVal: '',
      zFragment: [],
      locationForm: { name: '' },
      // 坐标轴配置
      axisTxt: {
        x: {
          name: 'X',
          color: '#f8f097'
        },
        y: {
          name: 'Y',
          color: '#06dd37'
        },
        z: {
          name: 'Z',
          color: '#e525e1'
        }
      },
      dialogForm: {
        domains: [],
        name: ''
      },
      currentAttrTypeId: null,
      attrTypeAllData: [],
      restaurants: [],
      currentAttrs: [],
      dialogFormVisible: false,
      dataLen: 90, // 数据量
      margin: 1.5, // 间距
      viewDistance: 0, // 视图距离
      column: 10, // 列数
      row: 3, // 行数
      zColumn: 3, // z列数
      left: 0.6, // 与左侧的距离
      top: 0.6, // 与顶部的距离
      deepness: 0.6, // 深度
      rowData: [],
      columnData: [],
      zColumnData: [],
      data: [{
        label: 'FJ',
        children: [
          {
            label: '子任务1',
            children: [{
              label: '三级任务1'
            }]
          }, {
            label: '子任务2',
            children: [{
              label: '三级任务2'
            }]
          }, {
            label: '子任务3',
            children: [{
              label: '三级任务3'
            }]
          }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created () {
    let marginSize = util.cookies.get('marginSize')
    let viewDistance = util.cookies.get('viewDistance')
    this.margin = Number(marginSize) + 1
    this.viewDistance = Number(viewDistance)
    getAttrTypeAll().then(data => {
      this.attrTypeAllData = data
    })
  },
  watch: {
    TXvalue () {
      this.getCanvasData(this.TXvalue)
    },
    currentAttrTypeId () {
      let DictQuery = {
        't': {
          'attributeTypeId': this.currentAttrTypeId
        }
      }
      getAttrList(DictQuery).then(res => {
        let newData = []
        res.list.filter((item, index) => {
          // item.value = item.val + '(' + item.attributeTypeName + ')'
          item.value = item.val
          newData[index] = item
        })
        this.restaurants = newData
      })
    }
  },
  methods: {
    sum (m, n) {
      var num = Math.floor(Math.random() * (m - n) + n)
      return num
    },
    substr (str, start, end) {
      let unit = 6 // 5个1组
      let arr = [] // 保存每次截取后的字符串
      let counts = Math.ceil(str.length / unit) // 循环截取的次数,向上取整

      for (let i = 0; i < counts; i++) {
        let newStr = str.substring(start, end)
        arr.push(newStr)
        start = end
        end += 6
      }
      return arr
    },
    createDefaultEngine (canvas) {
      return new vb.BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })
    },
    createScene (canvas, engine) {
      // Create the scene space
      let scene = new vb.BABYLON.Scene(engine)

      // Add a camera to the scene and attach it to the canvas
      /*
      * name: string 定义摄像机的名称
      * alpha: number 定义摄像机沿对数轴的旋转
      * beta: number 定义摄像机沿纬度轴的旋转
      * radius: number 定义相机到目标的距离
      * target: Vector3 定义相机目标
      * scene: Scene 定义相机所属的场景
      */
      // var camera = new vb.BABYLON.ArcRotateCamera("Camera", 5 * Math.PI / 2.007, Math.PI / 2.07, 86, vb.BABYLON.Vector3.Zero(), scene);
      let camera = new vb.BABYLON.ArcRotateCamera('Camera', 0, 0, 0, new vb.BABYLON.Vector3(this.xRotate, 3, 5), scene)

      camera.setPosition(new vb.BABYLON.Vector3(6, 3, -11.5 + this.viewDistance))
      camera.attachControl(canvas, true)
      // scene.useclonedmeshmap=true;
      // scene.useMaterialMeshMap=true;
      // scene.useGeometryIdsMap=true;
      // Add lights to the scene

      // 设置缩放区间
      camera.wheelDeltaPercentage = 0.01
      camera.attachControl(canvas, true)
      camera.lowerRadiusLimit = 10
      camera.upperRadiusLimit = 30

      /*
      * < BABYLON.HemisphericLight > 半球光 Parameters
      * name: string
      * 友好的灯名称
      *
      * direction: Vector3
      * 光反射的方向
      *
      * scene: Scene
      * 灯光所属的场景
      */
      let light1 = new vb.BABYLON.HemisphericLight('light1', new vb.BABYLON.Vector3(1, 1, 0), scene)

      /*
      * < BABYLON.PointLight > 点光源 Parameters
      * name: string
      * 名称
      *
      * position: Vector3
      * The position of the point light in the scene
      * 灯光在场景中的位置
      * scene: Scene
      * 灯光所属的场景
      */
      let light2 = new vb.BABYLON.PointLight('light2', new vb.BABYLON.Vector3(0, 1, -1), scene)

      let faceColors = []
      faceColors[0] = vb.BABYLON.Color3.Blue()
      faceColors[1] = vb.BABYLON.Color3.Red()
      faceColors[2] = vb.BABYLON.Color3.Green()
      faceColors[3] = vb.BABYLON.Color3.White()
      faceColors[4] = vb.BABYLON.Color3.Yellow()
      faceColors[5] = vb.BABYLON.Color3.Black()

      // Add and manipulate meshes in the scene
      // 方的
      // height 高度 （数字）高度尺寸，覆盖尺寸属性 尺寸
      // width 宽度 （数字）宽度大小，覆盖大小属性 尺寸
      // depth 深度 （数字）深度大小，覆盖大小属性 尺寸

      // 模拟当前数据量
      for (let i = 0; i < this.dataLen; i++) {
        // 序号
        // barLegendTexture.drawText(box.name, 20, 20, '400 16px Segoe UI', '#ff4c1e', '#fff')
        // 中间内容
        // barLegendTexture.drawText('Loading ' + box.name, null, 70, 'bold 16px Segoe UI', 'blue', null)
        let ids = this.rowData[i % this.row].id + ',' + this.columnData[(Math.floor(i / this.row) % this.column)].id + ',' + this.zColumnData[Math.floor(i / (this.row * this.column))].id
        getUnit(ids).then(data => {
          let box = vb.BABYLON.MeshBuilder.CreateBox(i, { height: 1, width: 1, depth: 1 }, scene)
          // 设置立方体位置
          let x = ((i % this.row) * this.margin) + this.left
          let y = ((Math.floor(i / this.row) % this.column) * this.margin) + this.top
          let z = (Math.floor(i / (this.row * this.column))) * this.margin + this.deepness
          box.position.x = x
          box.position.y = y
          box.position.z = z

          // 给某个盒子设置颜色
          // materialBox.diffuseColor = new vb.BABYLON.Color3(0.89, 0.23, 0.61, 0.77)
          // materialBox.diffuseColor = new vb.BABYLON.Color3(0.89, 0.79, 0.23, 0.79)
          // materialBox.diffuseColor = new vb.BABYLON.Color3(0.89, 0.71, 0.23, 0.79)
          // 设置颜色
          let materialBox = new vb.BABYLON.StandardMaterial('boxMaterial', scene)
          // 给某个盒子设置颜色
          materialBox.diffuseColor = new vb.BABYLON.Color3(0.06, 0.62, 0.99, 0.71)
          materialBox.emissiveColor = new vb.BABYLON.Color3(0.89, 0.23, 0.61).scale(0.8)
          materialBox.specularColor = new vb.BABYLON.Color3(0.88, 0.03, 0.03)
          // 设置颜色
          box.material = materialBox
          // 创建盒子文字
          let barLegend = vb.BABYLON.Mesh.CreateGround('barLegend', scene)
          barLegend.position.x = box.position.x
          barLegend.position.y = box.position.y
          barLegend.position.z = box.position.z
          // console.log(box.position.x,box.position.y+1, box.position.z)
          // box.material = new BABYLON.StandardMaterial("", scene);
          let barLegendTexture = new vb.BABYLON.DynamicTexture('title texture', 140, scene, true)
          barLegendTexture.hasAlpha = true
          box.material.diffuseTexture = barLegendTexture
          box.material.emissiveColor = new vb.BABYLON.Color3(0.4, 0.4, 0.4)
          // 必须得加三层，否则背景颜色失效
          // if (typeof data.name === 'undefined') {
          // 如果没有name 则拼接轴刻度信息作为默认值
          {
            let x = this.rowData[i % this.row]
            let y = this.columnData[Math.floor(i / this.row) % this.column]
            let z = this.zColumnData[Math.floor(i / (this.row * this.column))]
            barLegendTexture.drawText('', 20, 20, '400 16px Segoe UI', '#ff4c1e', '#fff')
            barLegendTexture.drawText(x.name, null, 40, 'bold 16px 微软雅黑', '#000909', '#fff')
            barLegendTexture.drawText(y.name, null, 70, 'bold 16px 微软雅黑', '#000909', null)
            barLegendTexture.drawText(z.name, null, 100, 'bold 16px 微软雅黑', '#000909', null)
          }
          // } else {
          //   barLegendTexture.drawText('', 20, 20, '400 16px Segoe UI', '#ff4c1e', '#fff')
          //   if (typeof data.name === 'string') {
          //     let arr = this.substr(data.name, 0, 6)
          //     // arr.forEach(e => {
          //     //   // console.log(e)
          //     //   barLegendTexture.drawText(e, null, 70, 'bold 16px 微软雅黑', '#000909', null)
          //     // })
          //     if (arr.length > 1) {
          //       for (let i = 0; i < arr.length; i++) {
          //         barLegendTexture.drawText(arr[i], null, (i + 1) * 30, 'bold 16px 微软雅黑', '#000909', null)
          //       }
          //     } else {
          //       barLegendTexture.drawText(arr[0], null, 70, 'bold 16px 微软雅黑', '#000909', null)
          //     }
          //   }
          //   barLegendTexture.drawText('', null, 120, '20px Segoe UI', 'blue', null)
          // }
          // console.log(this.rowData[i % this.row])
          // console.log((Math.floor(i / this.row) % this.column))
          // console.log((Math.floor(i / (this.row * this.column))))
          // console.log((Math.floor(i / this.row) % this.column))
          // console.log(this.columnData[(Math.floor(i / this.row) % this.column)])
          box.material.metadata = {
            x: this.rowData[i % this.row],
            y: this.columnData[(Math.floor(i / this.row) % this.column)],
            z: this.zColumnData[Math.floor(i / (this.row * this.column))]
          }

          // barLegendTexture.drawText(data.name, null, 70, 'bold 16px 宋体', 'white', null)
          // 给盒子绑定点击事件
          box.actionManager = new vb.BABYLON.ActionManager(scene)
          // new vb.BABYLON.ExecuteCodeAction 创建一个执行代码
          box.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
            // 动画

            // box.actionManager
            //   .registerAction(
            //     new vb.BABYLON.InterpolateValueAction(
            //       vb.BABYLON.ActionManager.OnPickTrigger,
            //       camera,
            //       'rotation',
            //       camera.setPosition(new vb.BABYLON.Vector3(this.xRotate + 10, 3, -11.5 + this.viewDistance)),
            //       90
            //     )
            //   )
            // console.log('耗时' + this.sum(90, 99) / 100 + '毫秒')

            this.currentAttrs = []
            // console.log(event.source.id)
            // console.log(event.source.material.metadata, 111)
            // 点击的时候先根据ids查询单元信息进行回显
            let ids = event.source.material.metadata.x.id + ',' + event.source.material.metadata.y.id + ',' + event.source.material.metadata.z.id
            this.currentUnitIds = ids.split(',')
            this.currentUnitInformation = event.source.material.metadata
            // console.log(ids, 'ids')
            getUnit(ids).then((data) => {
              this.currentAttrs = data.attributes || []
              let id = data.id || ''
              this.keys = {
                scaleIds: this.currentUnitIds,
                id: id,
                attribute_id: [],
                name: data.name,
                mean: data.mean,
                target: data.target,
                attributes: data.attributes,
                xName: event.source.material.metadata.x.parent_name,
                x: event.source.material.metadata.x.name,
                y: event.source.material.metadata.y.name,
                yName: event.source.material.metadata.y.parent_name,
                zName: event.source.material.metadata.z.parent_name,
                z: event.source.material.metadata.z.name
              }
            })
            document.querySelector('.floatingFrame').style.display = 'block'
          }))

          // 图例设置

          let blueMat = new vb.BABYLON.StandardMaterial('blue', scene)
          blueMat.diffuseColor = new vb.BABYLON.Color3(0, 0, 1, 0.77)

          let redMat = new vb.BABYLON.StandardMaterial('red', scene)
          redMat.diffuseColor = new vb.BABYLON.Color3(1, 0, 0, 0.77)
        })
        // 底下内描述
        // barLegendTexture.drawText('( statistics ' + box.name + ')', null, 120, '20px Segoe UI', 'blue', null)
      }
      // 添加背景色
      // scene.clearColor = new vb.BABYLON.Color4(0, 0, 0, 0)
      // 背景色
      scene.clearColor = new vb.BABYLON.Color4(0.07, 0.18, 0.23, 0.90)
      // 图片背景
      // var skybox = vb.BABYLON.Mesh.CreateBox('BackgroundSkybox', 400, scene, undefined, vb.BABYLON.Mesh.BACKSIDE)
      //
      // // Create and tweak the background material.
      // var backgroundMaterial = new vb.BABYLON.BackgroundMaterial('backgroundMaterial', scene)
      // backgroundMaterial.reflectionTexture = new vb.BABYLON.CubeTexture('textures/img', scene)
      // backgroundMaterial.reflectionTexture.coordinatesMode = vb.BABYLON.Texture.SKYBOX_MODE
      // skybox.material = backgroundMaterial
      this.camera = camera
      this.dom = light1
      this.scene = scene

      /****************************************************************/
      /*  轴线  */

      // showAxis 参数要加上每个方块的margin
      // this.showAxis(10 + 9 * 1.5, 3 + 2 * 1.5, 3 + 2 * 1.5, scene)
      // row
      // column
      // zColumn
      // console.log(this.column, 111)
      this.showAxis(this.row * this.margin + 1.5, this.column * this.margin + 1.5, this.zColumn * this.margin + 1.5, scene)

      /****************************************************************/

      return scene
    },
    showAnimation (light1, camera, scene) {
      light1.actionManager = new vb.BABYLON.ActionManager(scene)
      light1.actionManager
        .registerAction(
          new vb.BABYLON.InterpolateValueAction(
            vb.BABYLON.ActionManager.OnPickTrigger,
            camera,
            'rotation',
            camera.setPosition(new vb.BABYLON.Vector3(this.xRotate + 10, 3, -11.5 + this.viewDistance)),
            90
          )
        )
      console.log('耗时' + this.sum(90, 99) / 100 + '毫秒')
    },
    showAxis (xSize, ySize, zSize, scene) {
      let makeTextPlane = function (text, color, size) {
        let dynamicTexture = new vb.BABYLON.DynamicTexture('DynamicTexture', 140, scene, true)
        dynamicTexture.hasAlpha = true
        dynamicTexture.drawText(text, 20, 60, '400 18px 微软雅黑', color, 'transparent', true)
        let plane = new vb.BABYLON.Mesh.CreatePlane('TextPlane', size, scene, true)
        plane.material = new vb.BABYLON.StandardMaterial('TextPlaneMaterial', scene)
        plane.material.backFaceCulling = false
        plane.material.specularColor = new vb.BABYLON.Color3(0, 0, 0)
        plane.material.diffuseTexture = dynamicTexture
        return plane
      }

      // Vector3(size, 0, 0) x,y,z
      // 画线 现在有三个点(0, 0, 0), (0, 1, 1), (0, 1, 0)，它们可以形成两个线段。
      let lineAngle = 3.3
      let axisX = vb.BABYLON.Mesh.CreateLines('axisX', [
        new vb.BABYLON.Vector3.Zero(), new vb.BABYLON.Vector3(xSize, 0, 0), new vb.BABYLON.Vector3(xSize * 0.95, 0.05 * lineAngle, 0),
        new vb.BABYLON.Vector3(xSize, 0, 0), new vb.BABYLON.Vector3(xSize * 0.95, -0.05 * lineAngle, 0)
      ], scene)
      // axisX.color = new vb.BABYLON.Color3(1, 0, 0)
      axisX.color = new vb.BABYLON.Color3(0.97, 0.99, 0.06)
      let xChar = makeTextPlane(this.axisTxt.x.name, this.axisTxt.x.color, 2)
      xChar.position = new vb.BABYLON.Vector3(0.9 * xSize, -0.08 * xSize, 0)
      let axisY = vb.BABYLON.Mesh.CreateLines('axisY', [
        new vb.BABYLON.Vector3.Zero(), new vb.BABYLON.Vector3(0, ySize, 0), new vb.BABYLON.Vector3(-0.05 * lineAngle, ySize * 0.95, 0),
        new vb.BABYLON.Vector3(0, ySize, 0), new vb.BABYLON.Vector3(0.05 * lineAngle, ySize * 0.95, 0)
      ], scene)
      axisY.color = new vb.BABYLON.Color3(0, 1, 0)
      let yChar = makeTextPlane(this.axisTxt.y.name, this.axisTxt.y.color, 2)
      yChar.position = new vb.BABYLON.Vector3(0, 0.9 * ySize, -0.05 * ySize)
      let axisZ = vb.BABYLON.Mesh.CreateLines('axisZ', [
        new vb.BABYLON.Vector3.Zero(), new vb.BABYLON.Vector3(0, 0, zSize), new vb.BABYLON.Vector3(0, -0.05 * lineAngle, zSize * 0.95),
        new vb.BABYLON.Vector3(0, 0, zSize), new vb.BABYLON.Vector3(0, 0.05 * lineAngle, zSize * 0.95)
      ], scene)
      // axisZ.color = new vb.BABYLON.Color3(0, 0, 1)
      axisZ.color = new vb.BABYLON.Color3(0.99, 0.06, 0.86)
      let zChar = makeTextPlane(this.axisTxt.z.name, this.axisTxt.z.color, 2)
      zChar.position = new vb.BABYLON.Vector3(0, 0.05 * zSize, 0.9 * zSize)

      // BABYLON.ActionManager.NothingTrigger：从不提出。用于具有action.then功能的子动作。
      // BABYLON.ActionManager.OnPickTrigger：当用户触摸/单击网格时引发。
      // BABYLON.ActionManager.OnDoublePickTrigger：在用户双击/单击网格时引发。
      // BABYLON.ActionManager.OnPickDownTrigger：当用户触摸/点击网格时引发
      // BABYLON.ActionManager.OnPickUpTrigger：当用户触摸/单击网格时引发。
      // BABYLON.ActionManager.OnPickOutTrigger：当用户触摸/向下单击网格然后移出网格时引发。
      // BABYLON.ActionManager.OnLeftPickTrigger：当用户使用左键触摸/单击网格时引发。
      // BABYLON.ActionManager.OnRightPickTrigger：当用户触摸/单击带有右键的网格时引发。
      // BABYLON.ActionManager.OnCenterPickTrigger：当用户触摸/单击带有中心按钮的网格时引发。
      // BABYLON.ActionManager.OnLongPressTrigger：当用户在毫秒内长时间触摸/单击网格时触发（由BABYLON.Scene.LongPressDelay定义）。
      // BABYLON.ActionManager.OnPointerOverTrigger：当指针在网格上方时引发。只举过一次。
      // BABYLON.ActionManager.OnPointerOutTrigger：当指针不再位于网格上方时引发。只举过一次。
      // BABYLON.ActionManager.OnIntersectionEnterTrigger：当网格与特定网格相交时引发。只举过一次。
      // BABYLON.ActionManager.OnIntersectionExitTrigger：当网格不再与特定网格相交时引发。只举过一次
      /* ========轴线刻度========= */
      let xheight = null
      let yheight = null
      // let zheight = null
      for (let i = 0; i < this.row; i++) {
        // 刻度名称
        // let arr = this.substr(data.name, 0, 6)
        let x = null
        let name = ''
        // 超过六个字符的换行显示
        if (this.rowData[i].name.length > 6) {
          let arr = this.substr(this.rowData[i].name, 0, 6)
          for (let j = 0; j < arr.length; j++) {
            let xkedu = makeTextPlane(arr[j], '#f8f097', 1.1)
            xkedu.metadata = this.rowData[i]
            x = ((i % this.row) * this.margin) + this.left
            xkedu.position = new vb.BABYLON.Vector3(x, -0.4 - (j * .18), 0)
            xkedu.actionManager = new vb.BABYLON.ActionManager(scene)
            xkedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
              // 弹窗编辑
              // this.$alert('你点击了刻度x')
              // console.log(event.meshUnderPointer.metadata)
              if (this.isPiecesData === false) {
                this.$EventBus.$emit('showTree', this.TXvalue)
                this.scaleShowDialog = true
              } else {
                let data = []
                data.push(event.meshUnderPointer.metadata)
                this.row = data.length
                this.dataLen = this.row * this.column * this.zColumn

                // 设置刻度信息
                this.rowData = data
                this.createView()
              }
            }))
          }
        } else {
          name = this.rowData[i].name
          let xkedu = makeTextPlane(name, '#f8f097', 1.1)
          xkedu.metadata = this.rowData[i]
          x = ((i % this.row) * this.margin) + this.left
          xkedu.position = new vb.BABYLON.Vector3(x, -0.4, 0)
          xkedu.actionManager = new vb.BABYLON.ActionManager(scene)
          xkedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
            // 弹窗编辑
            // this.$alert('你点击了刻度x')
            // console.log(event.meshUnderPointer.metadata)
            if (this.isPiecesData === false) {
              this.$EventBus.$emit('showTree', this.TXvalue)
              this.scaleShowDialog = true
            } else {
              let data = []
              data.push(event.meshUnderPointer.metadata)
              this.row = data.length
              this.dataLen = this.row * this.column * this.zColumn

              // 设置刻度信息
              this.rowData = data
              this.createView()
            }
          }))
        }
        let xlineScale = vb.BABYLON.Mesh.CreateLines('x' + i, [
          new vb.BABYLON.Vector3(x + (1 / 2), 0, 0),
          new vb.BABYLON.Vector3(x + (1 / 2), ySize - this.margin + this.top, 0)
        ], scene)
        // axisX.color = new vb.BABYLON.Color3(1, 0, 0)
        xlineScale.color = new vb.BABYLON.Color3(0.97, 0.99, 0.06)
        let XYZ = vb.BABYLON.Mesh.CreateLines('xyz' + i, [
          new vb.BABYLON.Vector3(x + (1 / 2), 0, 0),
          new vb.BABYLON.Vector3(x + (1 / 2), 0, zSize - this.margin + this.top)
        ], scene)
        XYZ.color = new vb.BABYLON.Color3(0.99, 0.06, 0.86) // 紫色
        xheight = x + (1 / 2)
      }
      for (let i = 0; i < this.column; i++) {
        let y = ((i % this.column) * this.margin) + this.top
        if (this.columnData[i].name.length > 6) {
          let arr = this.substr(this.columnData[i].name, 0, 6)
          for (let j = 0; j < arr.length; j++) {
            let ykedu = makeTextPlane(arr[j], '#06dd37', 1.1)
            ykedu.metadata = this.columnData[i]
            ykedu.position = new vb.BABYLON.Vector3(-0.6, y - (j * .18), 0)
            ykedu.actionManager = new vb.BABYLON.ActionManager(scene)
            ykedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
              // this.$alert('你点击了刻度y')
              if (this.isPiecesData === false) {
                this.$EventBus.$emit('showTree', this.TXvalue)
                this.scaleShowDialog = true
              } else {
                let data = []
                data.push(event.meshUnderPointer.metadata)
                this.column = data.length
                this.dataLen = this.row * this.column * this.zColumn

                // 设置刻度信息
                this.columnData = data
                this.createView()
              }
            }))
          }
        } else {
          let ykedu = makeTextPlane(this.columnData[i].name, '#06dd37', 1.1)
          ykedu.metadata = this.columnData[i]
          ykedu.position = new vb.BABYLON.Vector3(-0.6, y, 0)
          ykedu.actionManager = new vb.BABYLON.ActionManager(scene)
          ykedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
            // this.$alert('你点击了刻度y')
            if (this.isPiecesData === false) {
              this.$EventBus.$emit('showTree', this.TXvalue)
              this.scaleShowDialog = true
            } else {
              let data = []
              data.push(event.meshUnderPointer.metadata)
              this.column = data.length
              this.dataLen = this.row * this.column * this.zColumn

              // 设置刻度信息
              this.columnData = data
              this.createView()
            }
          }))
        }
        let xylineScale = vb.BABYLON.Mesh.CreateLines('y' + i, [
          new vb.BABYLON.Vector3(0, y + (1 / 2), 0),
          new vb.BABYLON.Vector3(xheight, y + (1 / 2), 0)
        ], scene)
        // axisX.color = new vb.BABYLON.Color3(1, 0, 0)
        xylineScale.color = new vb.BABYLON.Color3(0.97, 0.99, 0.06) // 黄色
        let yzlineScale = vb.BABYLON.Mesh.CreateLines('y' + i, [
          new vb.BABYLON.Vector3(0, y + (1 / 2), 0),
          new vb.BABYLON.Vector3(0, y + (1 / 2), zSize - this.margin + this.top)
        ], scene)
        yzlineScale.color = new vb.BABYLON.Color3(0, 1, 0) // 绿色
        // axisX.color = new vb.BABYLON.Color3(1, 0, 0)
        // let XYZ = vb.BABYLON.Mesh.CreateLines('xyz' + i, [
        //   new vb.BABYLON.Vector3(0, 0, xheight-this.margin),
        //   new vb.BABYLON.Vector3(0, y + (1 / 2), xheight-this.margin)
        // ], scene)
        // XYZ.color = new vb.BABYLON.Color3(0.99, 0.06, 0.86) // 紫色
        yheight = y + (1 / 2)
      }
      for (let i = 0; i < this.zColumn; i++) {
        let z = ((i % this.zColumn) * this.margin) + this.top
        if (this.zColumnData[i].name.length > 6) {
          let arr = this.substr(this.zColumnData[i].name, 0, 6)
          for (let j = 0; j < arr.length; j++) {
            let zkedu = makeTextPlane(arr[j], '#e525e1', 1.1)
            zkedu.metadata = this.zColumnData[i]
            zkedu.position = new vb.BABYLON.Vector3(-0.6, -0.2 - (j * .18), z)
            zkedu.actionManager = new vb.BABYLON.ActionManager(scene)
            zkedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
              // this.$alert('你点击了刻度z')
              if (this.isPiecesData === false) {
                this.$EventBus.$emit('showTree', this.TXvalue)
                this.scaleShowDialog = true
              } else {
                let data = []
                data.push(event.meshUnderPointer.metadata)
                this.zColumn = data.length
                this.dataLen = this.row * this.column * this.zColumn

                // 设置刻度信息
                this.zColumnData = data
                this.createView()
              }
            }))
          }
        } else {
          let zkedu = makeTextPlane(this.zColumnData[i].name, '#e525e1', 1.1)
          zkedu.metadata = this.zColumnData[i]
          zkedu.position = new vb.BABYLON.Vector3(-0.2, -0.2, z)
          zkedu.actionManager = new vb.BABYLON.ActionManager(scene)
          zkedu.actionManager.registerAction(new vb.BABYLON.ExecuteCodeAction(vb.BABYLON.ActionManager.OnPickUpTrigger, (event) => {
            // this.$alert('你点击了刻度z')
            if (this.isPiecesData === false) {
              this.$EventBus.$emit('showTree', this.TXvalue)
              this.scaleShowDialog = true
            } else {
              let data = []
              data.push(event.meshUnderPointer.metadata)
              this.zColumn = data.length
              this.dataLen = this.row * this.column * this.zColumn

              // 设置刻度信息
              this.zColumnData = data
              this.createView()
            }
          }))
        }
        let zylineScale = vb.BABYLON.Mesh.CreateLines('y' + i, [
          new vb.BABYLON.Vector3(0, 0, z + (1 / 2)),
          new vb.BABYLON.Vector3(0, yheight, z + (1 / 2))
        ], scene)
        // axisX.color = new vb.BABYLON.Color3(1, 0, 0)
        zylineScale.color = new vb.BABYLON.Color3(0, 1, 0) // 绿色
        // 上面
        let XZY = vb.BABYLON.Mesh.CreateLines('xzy' + i, [
          new vb.BABYLON.Vector3(0, 0, z + (1 / 2)),
          new vb.BABYLON.Vector3(xheight, 0, z + (1 / 2))
        ], scene)
        XZY.color = new vb.BABYLON.Color3(0.99, 0.06, 0.86) // 紫色
        // zheight = z + (1 / 2)
      }
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.dialogForm)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    removeDomain (item) {
      var index = this.dialogForm.domains.indexOf(item)
      if (index !== -1) {
        this.dialogForm.domains.splice(index, 1)
      }
    },
    removeUnit (item) {
      var index = this.keys.attributes.indexOf(item)
      if (index !== -1) {
        this.keys.attributes.splice(index, 1)
        this.currentAttrs = this.keys.attributes
      }
    },
    removeLocalUnit (item) {
      var index = this.locationForm.attributes.indexOf(item)
      if (index !== -1) {
        this.locationForm.attributes.splice(index, 1)
        this.currentAttrs = this.locationForm.attributes
      }
    },
    addDomain () {
      this.dialogForm.domains.push({
        value: '',
        key: Date.now()
      })
    },
    addAttr () {
      if (this.keys.id) {
        this.keys.attributes.push({
          key: Date.now()
        })
      } else {
        this.$message.warning('请先新增单元名称')
      }
    },
    addLocationAttr () {
      if (this.locationForm.id) {
        this.locationForm.attributes.push({
          name: '',
          key: Date.now()
        })
      } else {
        this.$message.warning('请先新增单元名称')
      }
    },
    handleNodeClick (data) {
      // 任务树节点点击
      this.dialogForm.name = data.label
      // console.log(data)
    },
    unitInformationClose () {
      //  单元信息框关闭
      document.querySelector('.floatingFrame').style.display = 'none'
    },
    base64DataURLToArrayBuffer (dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/
      if (!base64Regex.test(dataURL)) {
        return false
      }
      const stringBase64 = dataURL.replace(base64Regex, '')
      let binaryString
      if (typeof window !== 'undefined') {
        binaryString = window.atob(stringBase64)
      } else {
        binaryString = Buffer.from(stringBase64, 'base64').toString('binary')
      }
      const len = binaryString.length
      const bytes = new Uint8Array(len)
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i)
        bytes[i] = ascii
      }
      console.log(bytes.buffer)
      return bytes.buffer
    },
    // saveDocx (name, img) {
    //   let _this = this
    //   // 点击导出word
    //   // 读取并获得模板文件的二进制内容
    //   JSZipUtils.getBinaryContent('image.docx', (error, content) => {
    //     // input.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
    //     // 抛出异常
    //     if (error) {
    //       throw error
    //     }
    //
    //     // let opts = {}
    //     // opts.centered = true
    //     // opts.getImage = (chartId) => {
    //     //   console.log(chartId)
    //     //   return _this.base64DataURLToArrayBuffer(chartId)
    //     // }
    //     // opts.getSize = () => {
    //     //   // FOR FIXED SIZE IMAGE :
    //     //   return [150, 150]
    //     // }
    //
    //     // let imageModule = new ImageModule(opts)
    //     // 创建一个JSZip实例，内容为模板的内容
    //     let zip = new JSzip(content)
    //     // 创建并加载docxtemplater实例对象
    //     let doc = new Docx()
    //     doc.loadZip(zip)
    //     // .attachModule(imageModule)
    //     // .compile()
    //     // 设置模板变量的值
    //     doc.setData({
    //       image: img
    //     })
    //
    //     try {
    //       // 用模板变量的值替换所有模板变量
    //       doc.render()
    //     } catch (error) {
    //       // 抛出异常
    //       let e = {
    //         message: error.message,
    //         name: error.name,
    //         stack: error.stack,
    //         properties: error.properties
    //       }
    //       console.log(JSON.stringify({ error: e }))
    //       throw error
    //     }
    //
    //     // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
    //     let out = doc.getZip().generate({
    //       type: 'blob',
    //       mimeType:
    //         'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    //     })
    //     // 将目标文件对象保存为目标类型的文件，并命名
    //     saveAs.saveAs(out, name)
    //   })
    // },
    exportDocx (img, TXName, fileName, config, { title = document.title, width } = {}) {
      if (!img) return
      config = config || {}
      let copyDom = document.createElement('span')
      // const styleDom = document.querySelectorAll('style, link, meta')
      const titleDom = document.createElement('h1')
      titleDom.style.textAlign = 'center'
      titleDom.innerText = TXName

      copyDom.appendChild(titleDom)
      // Array.from(styleDom).forEach(item => {
      //   copyDom.appendChild(item.cloneNode(true))
      // })
      let dom = document.createElement('img')
      dom.src = img
      dom.width = '100%'
      // dom.style.height = '100px'
      const cloneDom = dom.cloneNode(true)
      copyDom.appendChild(cloneDom)

      const htmlTemp = copyDom.innerHTML
      copyDom = null
      // console.log('htmlTemp=', htmlTemp)
      let iframeDom = document.createElement('iframe')
      iframeDom.style.width = '100%'
      const attrObj = {
        height: 0,
        width: 0,
        border: 0,
        wmode: 'Opaque'
      }
      const styleObj = {
        position: 'absolute',
        top: '-999px',
        left: '-999px'
      }
      Object.entries(attrObj).forEach(([key, value]) => {
        iframeDom.setAttribute(key, value)
      })
      Object.entries(styleObj).forEach(([key, value]) => {
        iframeDom.style[key] = value
      })
      document.body.insertBefore(iframeDom, document.body.children[0])
      const iframeWin = iframeDom.contentWindow // 1.获取iframe中的window
      const iframeDocs = iframeWin.document // 2.获取iframe中的document
      iframeDocs.write(`<!doctype html>`)
      iframeDocs.write(htmlTemp)

      const htmlDoc = `
  <!DOCTYPE html>
  <html lang="en">
  <meta charset=utf-8>
  ${iframeDocs.documentElement.innerHTML}
  </html>
  `
      var converted = htmlDocx.asBlob(htmlDoc, config)
      saveAs(converted, fileName + '.docx')
      document.body.removeChild(iframeDom)
    },
    downloadSystemStructure () {
      let name = ''
      this.TXAllInformation.forEach((item) => {
        if (item.id === this.TXvalue) {
          name = item.name
        }
      })
      let _this = this
      html2canvas(document.querySelector('#renderCanvas'), { useCORS: true }).then(function (canvas) {
        // 获取年月日作为文件名
        let timers = new Date()
        let fullYear = timers.getFullYear()
        let month = timers.getMonth() + 1
        let date = timers.getDate()
        let randoms = Math.random() + ''
        // 年月日加上随机数
        let numberFileName = fullYear + '' + month + date + randoms.slice(3, 10)
        let imgData = canvas.toDataURL()
        // 保存图片
        let saveFile = function (data, filename) {
          let saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
          saveLink.href = data
          saveLink.download = filename

          var event = document.createEvent('MouseEvents')
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
          saveLink.dispatchEvent(event)
        }
        // 最终文件名+文件格式
        // console.log(imgData)
        // saveFile(imgData, filename)
        // _this.saveDocx(numberFileName, imgData)
        _this.exportDocx(imgData, name, numberFileName,
          {
            // orientation: 'landscape', margins: { top: 150 }
            margins: { top: 150 }
          }
        )
      })
    },
    getAll () {
      getSysAll().then(res => {
        this.TXAllInformation = res
        //  获取数据完成之后，选中第一条数据
        if (res.length > 0) {
          this.TXvalue = res[0].id
          // 获取数据渲染界面
        }
      })
    },
    createView () {
      // 创建视图
      let engine
      let scene
      let sceneToRender
      let canvas = document.getElementById('renderCanvas')

      try {
        engine = this.createDefaultEngine(canvas)
      } catch (e) {
        console.log('the available createEngine function failed. Creating the default engine instead')
        engine = this.createDefaultEngine(canvas)
      }
      if (!engine) throw new Error('engine should not be null.')
      scene = this.createScene(canvas, engine)
      sceneToRender = scene
      this.sceneToRender = sceneToRender
      engine.runRenderLoop(function () {
        if (sceneToRender) {
          sceneToRender.render()
        }
      })
      // Resize
      window.addEventListener('resize', function () {
        engine.resize()
      })
    },
    unitSaveOrUpdate () {
      //  单元信息更新
      this.keys.attributes = this.currentAttrs
      this.keys.name = '默认名'
      saveUnit(this.keys).then(() => {
        this.getCanvasData(this.TXvalue)
        getUnit(this.currentUnitIds).then((data) => {
          this.currentAttrs = data.attributes
          let id = data.id || ''
          this.keys = {
            scaleIds: this.currentUnitIds,
            id: id,
            attribute_id: [],
            name: data.name,
            mean: data.mean,
            target: data.target,
            attributes: data.attributes,
            xName: this.currentUnitInformation.x.parent_name,
            x: this.currentUnitInformation.x.name,
            y: this.currentUnitInformation.y.name,
            yName: this.currentUnitInformation.y.parent_name,
            zName: this.currentUnitInformation.z.parent_name,
            z: this.currentUnitInformation.z.name
          }
        })
        this.$message.success('单元信息保存成功！')
      })
    },
    getCanvasData (id) {
      getTXTree(id).then(data => {
        // console.log(data)
        if (data.length === 3) {
          // 设置每个轴的信息
          this.axisTxt = {
            x: {
              name: data[0].name,
              color: '#f8f097'
            },
            y: {
              name: data[1].name,
              color: '#06dd37'
            },
            z: {
              name: data[2].name,
              color: '#e525e1'
            }
          }

          // 设置数据量
          this.row = data[0].children.length
          this.column = data[1].children.length
          this.zColumn = data[2].children.length
          this.dataLen = this.row * this.column * this.zColumn
          // console.log(this.row, this.column, this.zColumn, this.dataLen)

          // 设置刻度信息
          this.rowData = data[0].children
          this.columnData = data[1].children
          this.zColumnData = data[2].children

          // dataLen: 90, // 数据量
          // margin: 1.5, // 间距
          // column: 10, // 列数
          // row: 3, // 行数
          // zColumn: 3, // z列数

          // // 设置分片数据
          // for (let i = 0; i < this.row.length; i++) {
          //   this.xFragment.push({ id: i, name: string })
          // }
          // console.log(this.xFragment)
          // for (let i = 0; i < this.column.length; i++) {
          //   this.yFragment.push({ id: i, name: i + 1 })
          // }
          // for (let i = 0; i < this.zColumn.length; i++) {
          //   this.zFragment.push({ id: i, name: i + 1 })
          // }

          this.createView()
          this.showUnitUnfold = true
        } else {
          this.$message.warning('该体系数据异常，请选择其他数据进行展示。')
        }
      })
    },
    unitLocation () {
      // 单元定位
      this.unitLocationIsShow = true
      // console.log(this.rowData.name)
      // this.columnData.name
      // this.zColumnData.name
      getTXTree(this.TXvalue).then(data => {
        // console.log(data)
        if (data.length === 3) {
          // 设置刻度信息
          this.locationXData = data[0]
          this.locationYData = data[1]
          this.locationZData = data[2]
          this.xData = this.locationXData.children
          this.yData = this.locationYData.children
          this.zData = this.locationZData.children
        } else {
          this.$message.warning('该体系数据异常，请选择其他数据进行展示。')
        }
      })
    },
    queryUnit () {
      //  开始定位
      if (this.xLocation !== '' && this.yLocation !== '' && this.zLocation !== '') {
        let ids = this.xLocation + ',' + this.yLocation + ',' + this.zLocation
        getUnit(ids).then(data => {
          this.locationForm = data
          this.currentAttrs = data.attributes || []
        })
      } else {
        this.$message.warning('请选择定位参数！')
      }
    },
    locationUnitSave () {
      let id = this.locationForm.id || ''
      let ids = this.xLocation + ',' + this.yLocation + ',' + this.zLocation
      this.locationForm.name = '默认名'
      this.locationForm.scaleIds = ids.split(',')
      this.locationForm.attributes = this.currentAttrs
      this.locationForm.id = id
      saveUnit(this.locationForm).then((data) => {
        let ids = this.xLocation + ',' + this.yLocation + ',' + this.zLocation
        getUnit(ids).then(data => {
          this.locationForm = data
          this.currentAttrs = data.attributes || []
        })
        // 注释是停止魔方刷新
        // this.getCanvasData(this.TXvalue)
        this.$message.success('数据更新成功')
      })
    },
    showUnitOr3DView () {
      // console.log(this.currentUnitInformation)
      let x = this.currentUnitInformation.x
      let y = this.currentUnitInformation.y
      let z = this.currentUnitInformation.z
      if (x.children.length > 0 && y.children.length > 0 && z.children.length > 0) {
        this.axisTxt = {
          x: {
            name: x.name,
            color: '#f8f097'
          },
          y: {
            name: y.name,
            color: '#06dd37'
          },
          z: {
            name: z.name,
            color: '#e525e1'
          }
        }

        // 设置数据量
        this.row = x.children.length
        this.column = y.children.length
        this.zColumn = z.children.length
        this.dataLen = this.row * this.column * this.zColumn
        // console.log(this.row, this.column, this.zColumn, this.dataLen)

        // 设置刻度信息
        this.rowData = x.children
        this.columnData = y.children
        this.zColumnData = z.children

        this.createView()
        // 关闭单元信息模块
        document.querySelector('.floatingFrame').style.display = 'none'
        console.log('耗时' + this.sum(90, 99) / 100 + '毫秒')
        this.showUnitUnfold = false
      } else {
        this.$message.warning('该单元数据不具备展示条件！')
      }
    },
    prewUp () {
      //  子单元返回上级
      this.getCanvasData(this.TXvalue)
      this.showUnitUnfold = true
    },
    spliceData () {
      //  数据切片显示
      this.isPiecesData = true
      this.$message.warning('请选择要切分的数据。')
    },
    closeSpliceData () {
      // 关闭数据切片功能
      this.isPiecesData = false
    },
    load3DView () {
      //  重新渲染界面
      this.isPiecesData = false
      this.getCanvasData(this.TXvalue)
    },
    querySearch (queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      if (results.length === 0) {
        this.showSaveBtn = true
      }
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (item) {
      let newData = []
      this.currentAttrs.forEach((i) => {
        if (i.id) {
          newData.push(i)
        }
      })
      this.currentAttrs = newData
      this.currentAttrs.push(item)
    },
    attrTypeChange (val) {
      //  当前添加的字典类型改变时 设置当前选中的类型
      this.currentAttrTypeId = val
      // this.currentAttrs = []
    },
    start () {
      this.xRotate += 10
      console.log('随机数')
    }
  },
  mounted () {
    // 获取体系架构信息列表
    window.vue = this
    this.getAll()
    this.$EventBus.$on('update3D', () => {
      this.getCanvasData(this.TXvalue)
    })
    this.$EventBus.$on('updateView', () => {
      let marginSize = util.cookies.get('marginSize')
      let viewDistance = util.cookies.get('viewDistance')
      this.margin = Number(marginSize) + 1
      this.viewDistance = Number(viewDistance)
      this.getCanvasData(this.TXvalue)
    })
  }
}
</script>

<style scoped>
.canvasParent {
  background-color: transparent;
  width: 100%;
  height: 100%;
  touch-action: none;
  overflow: hidden;
}

#renderCanvas {
  width: 100%;
  height: 100%;
  touch-action: none;
  overflow: hidden;
}

.selectBox {
  box-shadow: 0 0 10px rgba(51, 66, 91, 0.95);
  background-color: rgba(30, 44, 67, 0.95);
  padding: 5px;
  position: fixed;
}

.TXHeader, .LHeader {
  font-family: 微软雅黑;
  font-weight: bold;
  color: #4EFFFB;
}

.LHeader {
  font-size: 20px;
  color: #ff5500;
}

.canvasParent {
  position: relative;
}

.btn_Download {
  position: absolute;
  left: 20px;
  bottom: 20px;
}

.btn_Location {
  position: absolute;
  right: 20px;
  bottom: 20px;
}

.btn_prewUp {
  position: absolute;
  right: 170px;
  bottom: 20px;
}

.floatingFrame {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 0;
  z-index: 0;
  display: none;
}

.floatingFrame .main {
  color:#4EFFFB !important;
  padding: 20px;
  width: 40%;
  float: right;
  margin-top: 15px;
  margin-right: 15px;
  overflow-y: visible;
  border-radius: 5px;
  border: 1px solid rgba(142, 228, 208, 0.75);
  box-shadow: 0 0 10px rgba(142, 228, 208, 0.95);
  background: rgba(31, 45, 62, 0.8);
  font-size: 14px;
}

.main .title{
  font-size: 22px;
}

.floatingFrame .unitForm {
  height: 480px;
  overflow: auto;
}

#xDialogForm .el-input {
  margin-right: 10px;
  width: 70%;
  vertical-align: top;
}
</style>
